package com.cctv.haierstore.product.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cctv.haierstore.product.annotation.MallCache;
import com.cctv.haierstore.product.service.CategoryBrandRelationService;
import com.cctv.haierstore.product.vo.Catalog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cctv.common.utils.PageUtils;
import com.cctv.common.utils.Query;

import com.cctv.haierstore.product.dao.CategoryDao;
import com.cctv.haierstore.product.entity.CategoryEntity;
import com.cctv.haierstore.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> entities = categoryEntities.stream().filter(e -> e.getParentCid() == 0).map((menu) -> {
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {return( menu1.getSort()==null?0:menu1.getSort()) - ( menu2.getSort()==null?0:menu2.getSort());}).collect(Collectors.toList());
        return entities;
    }

    /**
     * 获取某一个菜单的子菜单
     * @param root 当前菜单
     * @param all 所有菜单
     * @return
     */
    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> list = all.stream().filter((e) -> e.getParentCid() == root.getCatId()).map((menu) -> {
            menu.setChildren(getChildrens(menu, all));
            return menu;
        }).sorted((menu1, menu2) -> {return( menu1.getSort()==null?0:menu1.getSort()) - ( menu2.getSort()==null?0:menu2.getSort());}).collect(Collectors.toList());

        return list;

    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeMenuByIds(List<Long> longs) {
        //TODO 根据业务删除
        baseMapper.deleteBatchIds(longs);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList();
        List<Long> parnentPath = fingParnentPath(catelogId, list);
        Collections.reverse(parnentPath);

        return  parnentPath.toArray(new Long[parnentPath.size()]);
    }

    private List<Long> fingParnentPath(Long categoryId,List<Long> paths){
        paths.add(categoryId);
        CategoryEntity byId = this.getById(categoryId);
        if(byId.getParentCid()!=0){
            fingParnentPath(byId.getParentCid(),paths);
        }
        return paths;
    }
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updaeCategory(category.getCatId(),category.getName());
    }

    @Override
    public List<CategoryEntity> getCategoryLevel1() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
//    @MallCache(key = "catelogJSON", lockName = "cates:lock", timeout = 30*60 , random = 10*60)
    @Cacheable(cacheNames = "catelogJSON", key = "#root.method.name")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
//        //1.加入缓存逻辑
//        String key = "catelogJSON";
//        String catelogJSON = redisTemplate.opsForValue().get(key);
//        if (StringUtils.isEmpty(catelogJSON)){
//            //2.缓存中没有,先上锁
//            RLock lock = redissonClient.getLock("cates:lock");
//            lock.lock(30l, TimeUnit.SECONDS);
//            try {
//                //3.双查缓存，如果有直接返回
//                catelogJSON = redisTemplate.opsForValue().get(key);
//                if(StringUtils.isNotEmpty(catelogJSON)){
//                    return JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
//                    });
//                }
//                //4.没有的话查询数据库
//                Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
//                //5.查到的数据再放入缓存,将对象转为json放在缓存中
//                catelogJSON = JSON.toJSONString(catalogJsonFromDb);
//                long ttl = 1800 + new Random().nextInt(200);
//                if (StringUtils.isEmpty(catelogJSON)) {
//                    ttl = new Random().nextInt(500);
//                }
//                redisTemplate.opsForValue().set("catelogJSON", catelogJSON, ttl, TimeUnit.SECONDS);
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                lock.unlock();
//            }
//        }
        Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
        String catelogJSON = JSON.toJSONString(catalogJsonFromDb);
        Map<String, List<Catalog2Vo>> result = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return result;
    }


    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDb() {
        // 一次性获取所有 数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        System.out.println("调用了 getCatalogJson  查询了数据库........【三级分类】");
        // 1）、所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        // 2）、封装数据
        Map<String, List<Catalog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), level1 -> {
            // 查到当前1级分类的2级分类
            List<CategoryEntity> category2level = getParent_cid(selectList, level1.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (category2level != null) {
                catalog2Vos = category2level.stream().map(level12 -> {
                    // 查询当前2级分类的3级分类
                    List<CategoryEntity> category3level = getParent_cid(selectList, level12.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (category3level != null) {
                        catalog3Vos = category3level.stream().map(level13 -> {
                            return new Catalog2Vo.Catalog3Vo(level12.getCatId().toString(), level13.getCatId().toString(), level13.getName());
                        }).collect(Collectors.toList());
                    }
                    return new Catalog2Vo(level1.getCatId().toString(), catalog3Vos, level12.getCatId().toString(), level12.getName());
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return collect;
    }

    /**
     * 查询出父ID为 parent_cid的List集合
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", level.getCatId()));
    }
}